package com.mingqijia.gassafety.job.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.SendMessagePhonesVo;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.job.dto.CallTaskDTO;
import com.mingqijia.gassafety.job.dto.SendMessageDTO;
import com.mingqijia.gassafety.job.service.AicallTaskService;
import com.mingqijia.gassafety.job.response.VccUserRseponse;
import com.mingqijia.gassafety.job.service.ConsumerService;
import com.mingqijia.gassafety.job.strategy.RecordService;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.constant.warnStrategy.WarnStrategyConst;
import com.mingqijia.gassafety.shared.dto.AssembleTemplateDTO;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.SnowflakeUtil;
import com.mingqijia.gassafety.shared.utils.message.SendMessageService;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


/**
 * @author mby
 * @version 1.0.0
 * @ClassName ServicePeriodStrategyServiceImpl.java
 * @Description
 * @createTime 2024年01月25日
 */

@Component
@Slf4j
public class ServicePeriodStrategyServiceImpl {

    @Autowired
    RedisCache redisCache;
    @Autowired
    ConsumerMapper consumerMapper;
    @Autowired
    CustomerSubsMapper customerSubsMapper;
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    RunningStrategyExtMapper extMapper;
    @Autowired
    ContactsMapper contactsMapper;
    @Autowired
    SendMessageService sendMessageService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    DictionaryMapper dictionaryMapper;
    @Autowired
    RunningStrategyMapper warnStrategyMapper;

    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    CompanyServiceImpl companyService;

    @Autowired
    DevicebindingServiceImpl devicebindingService;
    @Autowired
    BusinessNoticeMapper noticeMapper;

    @Autowired
    InformRecordMapper informRecordMapper;
    @Autowired
    RunningRecordMapper runningRecordMapper;
    @Autowired
    ReceiverValveMapper receiverValveMapper;

    @Autowired
    XFCallServiceImpl xFCallService;

    @Autowired
    AicallTaskService aicallTaskService;

    @Value(value = "${gassafety.warnStrategy.switch}")
    private boolean sw;
    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    VccAuthoritiesProvider provider;

    @Autowired
    DeviceStateMapper deviceStateMapper;
    @Autowired
    DtuBindingOrderMapper dtuBindingOrderMapper;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    CallTaskServiceImpl callTaskService;
    @Autowired
    RecordReceiverValveMapper recordReceiverValveMapper;

    public static final String CM_SERVICE_HOT_LINE = "cm_service_hot_line";

    /**
     * 保存服务提醒通知记录
     * @param dto 服务提醒基础数据
     * @param date 时间
     * @param errorMessage 错误信息
     * @param receiptCode 回执编码
     * @param sendResult 发送结果
     * @param status 执行状态
     */
    public void saveWarningRecord(SendMessageDTO dto, Date date, String errorMessage, String receiptCode, Integer sendResult, Integer status) {
        InformRecord warningRecord = new InformRecord();
        warningRecord.setConsumerId(String.valueOf(dto.getConsumerId()));
        warningRecord.setStartTime(date);
        warningRecord.setEndTime(date);
        warningRecord.setTriggerRuleId(dto.getStrategyId());
        warningRecord.setIMEI(dto.getImei());
        warningRecord.setTaskIdentificationCode(String.valueOf(dto.getSnowflakeId()));
        warningRecord.setSendType(dto.getPushType());
        warningRecord.setObjLevel(dto.getLevel());
        warningRecord.setSpId(dto.getSpId());
        warningRecord.setSendResult(sendResult);
        warningRecord.setStatus(status);
        warningRecord.setContent(dto.getContent());
        warningRecord.setReceiptCode(receiptCode);
        warningRecord.setPushPhone(dto.getPhone());
        warningRecord.setRemark(!StringUtils.isEmpty(errorMessage) ? errorMessage : "发送成功");
        log.info("saveWarningRecord:{}", JSONObject.toJSONString(warningRecord));
        informRecordMapper.insert(warningRecord);
    }

    /**
     * 信息发送判定，组装数据
     * @param pushType 推送方式
     * @param pushServicePeriodLevel 服务到期等级
     * @param service 服务信息
     * @param ext  策略信息
     * @param data 组装的发送数据
     * @param date 时间
     * @param orgName 公司名称
     * @param orgPhone 公司电话
     * @param snowflakeId uuid
     * @param cacheMap 缓存
     */
    public void predicateServicePeriod(MessagePushTypeEnum pushType, PushServicePeriodLevelEnum pushServicePeriodLevel, ConsumerServiceInfo service,
                                       RunningStrategyExt ext, List<SendMessageDTO> data, Date date, String orgName, String orgPhone,
                                       Long snowflakeId, Map<String, Object> cacheMap, RunningStrategy strategy) {
        if (ext == null) {
            log.info("runningServicePeriodStrategy-查找不到对应策略：IMEI：{}，consumerId：{}，pushType：{}，pushServicePeriodLevel：{}",
                    service.getImei(), service.getConsumerId(), pushType.getCode(), pushServicePeriodLevel.getCode());
            return ;
        }
        // 是否在时间范围内
        DtuPushTypeEnum pushTypes = DtuPushTypeEnum.getPushTypes(ext.getPushTime());
        Integer[] integers = pushTypes.getIntegers();
        int hours = new Date().getHours();
        log.info("runningServicePeriodStrategy-dateLong{}", date.getTime());
        if (integers.length != 2 || hours < integers[0] || hours > integers[1]) {
            log.info("runningServicePeriodStrategy-不在推送时间范围内：IMEI：{}，hours：{},integers：{}", service.getImei(), hours, integers);
            return ;
        }
        // 判断发送频率
        log.info("runningServicePeriodStrategy-getCacheMap:key:{},cacheMap:{}",Constants.WARNING_SERVICE_PERIOD_RUNNING + ":" + service.getImei(), cacheMap);
        if (cacheMap != null && cacheMap.get(pushServicePeriodLevel.getValue()+pushType.getValue()+"Time") != null
                && !checkSendRun(date, date.getTime(), (Long) cacheMap.get(pushServicePeriodLevel.getValue()+pushType.getValue()+"Time"), ext.getPushServiceExpireLevel(), ext.getPushFrequency())) {
            //如果为null,第一次发送，可发送
            log.info("runningServicePeriodStrategy-未满足推送频率：IMEI：{}，{}：{}，nowTime：{}", service.getImei(),pushServicePeriodLevel.getValue()+pushType.getValue()+"Time", cacheMap.get(pushServicePeriodLevel.getValue()+pushType.getValue()+"Time"), date.getTime());
            return ;
        } else {
            cacheMap.put(pushServicePeriodLevel.getValue()+pushType.getValue()+"Time", date.getTime());
        }

        List<SendMessagePhonesVo> phones = new ArrayList<>();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ext.getPushLevel()) && !"0".equals(ext.getPushLevel())){
            List<SendMessagePhonesVo> contractPhoneList= contactsMapper.selectServicePeriodPhones(service.getConsumerId(), Arrays.asList(ext.getPushLevel().split(";")));
            if (CollectionUtils.isNotEmpty(contractPhoneList)) {
                phones.addAll(contractPhoneList);
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ext.getPushPhones())){
            for (String phone : ext.getPushPhones().split(";")) {
                SendMessagePhonesVo vo = new SendMessagePhonesVo();
                vo.setTelephone(phone);
                vo.setLevel(ext.getPushLevel());
                phones.add(vo);
            }
        }

        String orgCode = companyService.getOrgCode(service.getSpId(), String.valueOf(service.getConsumerId()));
        QueryWrapper<Consumer> consumerQuery = new QueryWrapper<>();
        consumerQuery.lambda().eq(Consumer::getIsDeleted, 0)
                .eq(Consumer::getSpId, service.getSpId())
                .eq(Consumer::getId, service.getConsumerId());
        Consumer consumer = consumerService.getOne(consumerQuery);

        QueryWrapper<Dtu> dtuQuery = new QueryWrapper<>();
        dtuQuery.lambda().eq(Dtu::getIsDeleted, 0)
                .eq(Dtu::getSpId, service.getSpId())
                .eq(Dtu::getConsumerId, service.getConsumerId())
                .eq(Dtu::getIMEI, service.getImei());
        Dtu dtu = equipmentService.getOne(dtuQuery);
        SendMessageDTO dto = new SendMessageDTO();
        dto.setServiceStatus(pushServicePeriodLevel.getCode());
        dto.setVerb(pushServicePeriodLevel.getVerb());
        dto.setEndDate(DateUtils.dateFormat(service.getEndDate()));
        dto.setConsumerId(service.getConsumerId());
        dto.setSpId(service.getSpId());
        dto.setImei(service.getImei());
        dto.setKey(Constants.WARNING_SERVICE_PERIOD_RUNNING + ":" + service.getImei());
        dto.setStrategyId(ext.getStrategyId());
        dto.setStrategyType(strategy.getStrategyType());
        dto.setPushType(pushType.getCode());
        dto.setPushTypeCode(pushType.getValue());
        dto.setStrategyId(ext.getStrategyId());
        dto.setPhones(phones);
        dto.setOrgCode(orgCode);
        dto.setOrgName(orgName);
        dto.setExt(ext);
        dto.setSnowflakeId(snowflakeId);
        dto.setCacheMap(cacheMap);
        String factoryName = equipmentService.getEquipmentManufacturerName(dtu.getEquipmentManufacturer(),service.getSpId());
        dto.setFactoryName(factoryName);
        Map<String, Object> param = new HashMap<>();
        dto.setParam(param);
        param.put("verb", dto.getVerb());
        param.put("Time", dto.getEndDate());
        param.put("phone", orgPhone);
        param.put("position", Constants.BLANK);
        param.put("address", Constants.BLANK);
        param.put("subsName", Constants.BLANK);
        param.put("subsCode", Constants.BLANK);
        if (dtu != null) {
            dto.setPosition(dtu.getInstallationPosition());
            param.put("position", dtu.getInstallationPosition() == null ? Constants.BLANK : dtu.getInstallationPosition());
        }
        dto.setOrgPhone(orgPhone);
        if (consumer != null) {
            dto.setAddress(consumer.getAddress());
            dto.setCustName(consumer.getCustName());
            dto.setSubsCode(consumer.getSubsCode());
            dto.setName(consumer.getName());
            param.put("address", pushType == MessagePushTypeEnum.SMS ? consumer.getAddress() : dtu.getInstallationPosition());
            if (param.get("address") == null) {
                param.put("address", Constants.BLANK);
            }
            param.put("subsName", consumer.getCustName() == null ? Constants.BLANK : consumer.getCustName());
            param.put("subsCode", consumer.getSubsCode() == null ? Constants.BLANK : consumer.getSubsCode());
            param.put("CustomerName",consumer.getName() == null ? Constants.BLANK : consumer.getName());
        }
        param.put("IMEI", dto.getImei());
        param.put("factoryName", factoryName);
        if (pushType == MessagePushTypeEnum.WX && param.get("address").toString().length() > 20) {
            param.put("address", param.get("address").toString().substring(0, 20)); // 联系人地址
        }
        if (pushType == MessagePushTypeEnum.WX &&
            param.get("subsName").toString().length() > 18 - param.get("subsCode").toString().length()) {
            param.put("subsName", param.get("subsName").toString().substring(0, 15 - param.get("subsCode").toString().length()) + "..."); // 联系人地址
        }
        AssembleTemplateDTO assembleTemplate = new AssembleTemplateDTO();
        assembleTemplate.setSpId(dto.getSpId());
        assembleTemplate.setOrgCode(dto.getOrgCode());
        if (pushType == MessagePushTypeEnum.SMS) {
            dto.setSendCode(SMSTypeEnum.getPushTypes(dto.getStrategyType() == null ? StrategyTypeEnum.DEVICE_EXPIRATION.getCode() : dto.getStrategyType()).getName());
            if (!StringUtils.isEmpty(strategy.getSmsMsgCode())) {
                assembleTemplate.setSmsMsgCode(strategy.getSmsMsgCode());
                dto.setSendCode(strategy.getSmsMsgCode());
            }
            String content = sendMessageService.getSmsContent(dto.getSendCode(), param, assembleTemplate);
            dto.setContent(content);
            //dto.setContent(getSmsTemplate(dto, orgPhone));
        } else  if (pushType == MessagePushTypeEnum.WX) {
            dto.setSendCode(WxTypeEnum.getPushTypes(dto.getStrategyType() == null ? StrategyTypeEnum.DEVICE_EXPIRATION.getCode() : dto.getStrategyType()).getName());
            if (!StringUtils.isEmpty(strategy.getWxMsgCode())) {
                assembleTemplate.setWxMsgCode(strategy.getWxMsgCode());
                dto.setSendCode(strategy.getWxMsgCode());
            }
            String content = sendMessageService.getWxContent(dto.getSendCode(), param, assembleTemplate);
            dto.setContent(content);
            //dto.setContent(getWxTemplate(dto));
        } else  if (pushType == MessagePushTypeEnum.CALL) {
            dto.setContent(getCallTemplate(dto, Constants.WARNING_CALL_SERVICE_PERIOD, orgPhone));
        }
        if (pushServicePeriodLevel == PushServicePeriodLevelEnum.PERIOD) {
            log.info("runningServicePeriodStrategy-服务信息状态： 期至-count_eq{},此规则推送次数上限：{}", cacheMap.get(pushType.getType()+"count_eq") == null ? 1 : Integer.parseInt(cacheMap.get(pushType.getType()+"count_eq") + "") + 1, ext.getPushNumber());
            if (cacheMap != null && cacheMap.size() > 0 && cacheMap.get(pushType.getType()+"count_eq") != null && Integer.parseInt(cacheMap.get(pushType.getType()+"count_eq") + "") + 1 > ext.getPushNumber()) {
                saveWarningRecord(dto, new Date(), "此规则推送次数已超限", "", 1,1);
                return ;
            } else {
                // 发送次数
                cacheMap.put(pushType.getType()+"count_eq", cacheMap.get(pushType.getType()+"count_eq") == null ? 1 : Integer.parseInt(cacheMap.get(pushType.getType()+"count_eq") + "") + 1 );
            }
        }  else if (pushServicePeriodLevel == PushServicePeriodLevelEnum.EXPIRED) {
            log.info("runningServicePeriodStrategy-服务信息状态： 超期-count_lt{},此规则推送次数上限：{}", cacheMap.get(pushType.getType()+"count_lt") == null ? 1 : Integer.parseInt(cacheMap.get(pushType.getType()+"count_lt") + "") + 1, ext.getPushNumber());
            if (cacheMap != null && cacheMap.size() > 0 && cacheMap.get(pushType.getType()+"count_lt") != null && Integer.parseInt(cacheMap.get(pushType.getType()+"count_lt") + "") + 1 > ext.getPushNumber()) {
                saveWarningRecord(dto, new Date(), "此规则推送次数已超限", "", 1,1);
                cacheMap.put(pushType.getType()+"IsSend", 1);
                return ;
            } else if (cacheMap != null && cacheMap.size() > 0 && cacheMap.get(pushType.getType()+"count_lt") != null && Integer.parseInt(cacheMap.get(pushType.getType()+"count_lt") + "") + 1 == ext.getPushNumber()) {
                cacheMap.put(pushType.getType()+"IsSend", 1);
                cacheMap.put(pushType.getType()+"count_lt", cacheMap.get(pushType.getType()+"count_lt") == null ? 1 : Integer.parseInt(cacheMap.get(pushType.getType()+"count_lt") + "") + 1 );
            }else {
                cacheMap.put(pushType.getType()+"IsSend", ext.getPushNumber() == 1 ? 1 : 0);
                // 发送次数
                cacheMap.put(pushType.getType()+"count_lt", cacheMap.get(pushType.getType()+"count_lt") == null ? 1 : Integer.parseInt(cacheMap.get(pushType.getType()+"count_lt") + "") + 1 );
            }
        }
        if (pushType == MessagePushTypeEnum.WX && org.apache.commons.lang.StringUtils.isNotEmpty(dto.getSubsCode())
                && org.apache.commons.lang.StringUtils.isNotEmpty(dto.getOrgCode())) {
            log.info("ExpiredPredicateStrategy-getVccUser：subsCode：{},orgCode：{}", dto.getSubsCode(),dto.getOrgCode());
            VccUserRseponse vccUser = consumerService.getVccUser(dto.getSubsCode(), "", dto.getOrgCode());
            if (vccUser ==null ){
                log.info("ExpiredPredicateStrategy-getVccUser：vcc不存在");
            } else {
                log.info("ExpiredPredicateStrategy-getVccUser：{}", vccUser);
                dto.setPhone(vccUser.getCustPhone());
                dto.setLevel(ext.getPushLevel());
            }
        }
        data.add(dto);

    }

    private boolean checkSendRun(Date now, long nowTime, long sendTime, Integer pushServiceExpireLevel, Integer pushFrequency) {
        if (pushServiceExpireLevel == 2) {
            // 1小时  2小时
            if (nowTime - sendTime >= pushFrequency * 60 * 60 * 1000) {
                return true;
            }
        } else {
            if (pushFrequency == 1 && nowTime - sendTime >= 24  * 60 * 60 * 1000) {
                // 每日
                return true;
            } else if (pushFrequency == 2 && nowTime - sendTime >= 7 * 24  * 60 * 60 * 1000) {
                // 每周
                return true;
            } else if (pushFrequency == 3){
                if (nowTime >= DateUtil.offsetMonth(now, 1).getTime()) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean pushLocal(SendMessageDTO dto, String job, RecordService recordService) {
        try {

            //根据imei和用户id获得联系人姓名
            String contactName = "";
            if (StringUtil.isNotEmpty(dto.getMemberId())) {
                QueryWrapper<DtuBindingOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(DtuBindingOrder::getMemberId, dto.getMemberId())
                    .eq(DtuBindingOrder::getDeviceId, dto.getImei())  // 主体的IMEI
                    .eq(DtuBindingOrder::getIsDeleted, Constants.IS_DELETED_FALSE);
                List<DtuBindingOrder> orderList = dtuBindingOrderMapper.selectList(queryWrapper);
                log.info("{}-sendMessage-local-orderList:{}", job, JSONObject.toJSONString(orderList));
                try {
                    contactName = orderList.get(0).getCustName();
                } catch (Exception e) {
                    log.error("{}-sendMessage-local-error:{}", job, e);
                }
            }
            contactName = contactName == null ? "" : contactName;
            log.info("{}-sendMessage-local-memberId:{}", job, JSONObject.toJSONString(dto.getMemberId()));
            JSONObject object = new JSONObject();
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("notifyReason", "WarnStrategy");
            messageMap.put("notifyName", "设备触发报警策略");
            messageMap.put("notifyTime", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            messageMap.put("imei", dto.getImei());
            messageMap.put("installationPosition", dto.getPosition());
            messageMap.put("equipmentTypeName", EquipmentTypeConst.equipmentTypeMaps.get(dto.getEquipmentType()));
            messageMap.put("xlel", dto.getValue());
            messageMap.put("consumerId", dto.getConsumerId().toString());
            messageMap.put("custName", dto.getCustName());
            messageMap.put("subsCode", dto.getSubsCode());
            messageMap.put("isSystem", true);
            messageMap.put("isPop", true);
            messageMap.put("memberId", dto.getMemberId());
            messageMap.put("contactName", contactName);
            messageMap.put("equipmentFrom", dto.getEquipmentFrom());
            messageMap.put("pkgId", dto.getPkgId());
            if ( dto.getEquipmentFrom()==1){
                QueryWrapper<ReceiverValve> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().or().eq(ReceiverValve::getIsDeleted,0)
                        .eq(ReceiverValve::getDeviceId,dto.getImei());
                List<ReceiverValve> receiverValves = receiverValveMapper.selectList(queryWrapper);
                log.info("{}-sendMessage-local-receiverValves:{}", job, JSON.toJSONString(receiverValves));
                if (!CollectionUtil.isEmpty(receiverValves)) {
                    ReceiverValve receiverValve = receiverValves.get(0);
                    messageMap.put("valveStatus",receiverValve.getValveStatus() == 0 ? "正常" : "关闭");
                    messageMap.put("receiverStatus",receiverValve.getReceiverStatus() == 0 ? "离线" : "正常");
                }
                messageMap.put("phone",dto.getConsumerPhone());
            }
            object.put("spId", dto.getSpId());
            object.put("message", messageMap);

            //发送本地消息
            log.info("{}-sendMessage-local-again-object:{}", job, JSONObject.toJSONString(object));
            sendMessageService.sendLocalSms(object, dto.getSpId());
            recordService.saveWarningRecord(dto, new Date(), "发送成功", "", 0, 0);

        } catch (Exception e) {
            log.error("{}-sendMessage-local-error:{}", job, e);
        }
        return false;
    }

    public boolean pushSMS(SendMessageDTO dto, String job, RecordService recordService) {
        try {
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Object o = valueOperations.get(dto.getPushType().equals(MessagePushTypeEnum.SMS.getCode()) ? Constants.WARNING_PHONE_RUNNING : Constants.WARNING_PHONE + "-" + dto.getPhone());
            log.info("{}-sendMessage-sms-获取发送次数:telephone:{},发送次数:{}", job, dto.getPhone(), o);
            if (o != null && Integer.parseInt(o + "") >= 50) {
                recordService.saveWarningRecord(dto, new Date(), "此手机超过24小时发送次数", "", 1, 1);
                return true;
            }

            log.info("{}-sendMessage-sms-本次发送短信内容:{}:{}msgType:{}", job, dto.getPhone(), dto.getParam(), MessagePushTypeEnum.SMS.getType());
            if (StringUtils.isEmpty(dto.getPhone())) {
                recordService.saveWarningRecord(dto, new Date(), "手机号不能为空", "", 1, 1);
                return false;
            }
            //调用外部短信接口
            Map<String, Object> sms = sendMessageService
                .sendSms(sendMessageService
                    .getRequestParam(dto.getPhone()
                        , dto.getSendCode(), dto.getOrgCode()
                        , dto.getParam(), MessagePushTypeEnum.SMS.getType(), null, null, null, 0)
                        , "");
            Object errorMsg = null;
            try {
                if (sms.get("result") != null && sms.get("result").equals(true)) {
                    Integer count = 1;
                    if (o != null) {
                        count = Integer.parseInt(o + "") + 1;
                    }
                    valueOperations.set(Constants.WARNING_PHONE_RUNNING + "-" + dto.getPhone()
                        , count, 1L, TimeUnit.DAYS);
                }
                errorMsg = "";
                if (sms.get("data") != null) {
                    log.info("running—短信发送人；{}", dto.getPhone());
                    HashMap<String, Object> req = new HashMap<>();
                    req.put("ids", sms.get("data"));
                    req.put("orgCode", dto.getOrgCode());
                    try {
                        Map<String, Object> map = sendMessageService.subTaskDetail(req, "");
                        if (map != null) errorMsg = map.get("errorMsg");
                    } catch (Exception e) {
                        log.info("subTaskDetail-error:{}", e);
                    }
                    log.info("{}-sendMessage-sms-发送remark:{}", job, errorMsg);
                } else {
                    errorMsg = sms.get("errMsg");
                }
            } catch (Exception e) {
                log.error("{}-sendMessage-sms-error:{}", job, e);
            }

            recordService.saveWarningRecord(dto, new Date(), !StringUtils.isEmpty(errorMsg) ? errorMsg + "" : "发送成功",
                    StringUtils.isEmpty(sms.get("data")) ? "" : sms.get("data") + "", !StringUtils.isEmpty(errorMsg) ? 1 : 0, 0);
            log.info("{}-sendMessage-sms-发送日志:{}回执消息:{}", job, dto.getPhone(), JSONObject.toJSONString(sms));
        } catch (Exception e) {
            log.error("{}-sendMessage-sms-error:{}", job, e);
        }
        return false;
    }


    public void pushWx(SendMessageDTO dto, List<String> phones, String job, RecordService recordService) {
        log.info("{}-sendMessage-wx-imei:{},subsCode:{},phone:{}", job, dto.getImei(), dto.getSubsCode(), dto.getPhone());
        // C端预览的时候，链接地址不要加subsCode
        if (dto.getSendType() == 0) {
            dto.getParam().put("subsCode", Constants.BLANK);
        }
        Map<String, Object> sms = sendMessageService
            .sendSms(sendMessageService
                .getRequestParam(null
                    , dto.getSendCode(), dto.getOrgCode()
                    , dto.getParam(), MessagePushTypeEnum.WX.getType(), new ArrayList<>(), dto.getSubsCode(), phones, 0)
            , "");
        if (sms.get("result").equals(true)) {
            //发送成功
            String errorMsg = "发送成功";
            if (sms.get("data") != null) {
                HashMap<String, Object> req = new HashMap<>();
                req.put("ids", sms.get("data"));
                req.put("orgCode", dto.getOrgCode());
                Map<String, Object> resMap = sendMessageService.subTaskDetail(req, "");
                //延迟获取数据
                errorMsg = resMap != null ? (String) resMap.get("errorMsg") : "";
            }

            recordService.saveWarningRecord(dto, new Date(), !StringUtils.isEmpty(errorMsg) ? errorMsg + "" : "发送成功",
                JSONObject.toJSONString(sms.get("data")), !StringUtils.isEmpty(errorMsg) ? 1 : 0, 0);
            log.info("{}-sendMessage-wx-发送日志:{}回执消息:{}", job, dto.getPhone(), JSONObject.toJSONString(sms));
        } else {
            String errorMsg = (String)sms.get("errMsg");
            recordService.saveWarningRecord(dto, new Date(), !StringUtils.isEmpty(errorMsg) ? errorMsg + "" : "发送成功",
                    JSONObject.toJSONString(sms.get("data")), !StringUtils.isEmpty(errorMsg) ? 1 : 0, 0);
            log.info("{}-sendMessage-wx-发送日志:{}回执消息:{}", job, dto.getPhone(), JSONObject.toJSONString(sms));
        }
    }


    public void pushCall(SendMessageDTO dto, String job, RecordService recordService) {
        log.info("{}-sendCall:imei:{},phones:{}", job, dto.getImei(), dto.getPhones());
        CallTaskDTO callTaskDTO = aicallTaskService.getAicallTaskByType(dto.getStrategyType(), dto.getSpId());
        List<JSONArray> calls = new ArrayList<>();
        for (SendMessagePhonesVo vo : dto.getPhones()) {
            JSONArray array = new JSONArray();
            switch (job){
                case WarnStrategyConst.RUNNING_REPORT_INSTANTLY_JOB:
                case WarnStrategyConst.RUNNING_REPORT_JOB:
                    array.add(0, dto.getOrgName() == null ? Constants.BLANK : dto.getOrgName());
                    array.add(1, dto.getAddress() == null ? Constants.BLANK : dto.getAddress());
                    array.add(2, dto.getOrgName() == null ? Constants.BLANK : dto.getOrgName());
                    array.add(3, dto.getVerb()== null ? Constants.BLANK : dto.getVerb());
                    array.add(4, vo.getTelephone()== null ? Constants.BLANK : vo.getTelephone());
                    break;
                case WarnStrategyConst.RUNNING_SERVICE_PERIOD_JOB:
                    array.add(0, dto.getOrgName() == null ? Constants.BLANK : dto.getOrgName());
                    array.add(1, dto.getPosition() == null ? Constants.BLANK : dto.getPosition());
                    array.add(2, dto.getVerb() == null ? Constants.BLANK : dto.getVerb());
                    array.add(3, dto.getEndDate() == null ? Constants.BLANK : dto.getEndDate());
                    array.add(4, StringUtils.isEmpty(dto.getOrgPhone()) ? Constants.BLANK : dto.getOrgPhone());
                    array.add(5, vo.getTelephone()== null ? Constants.BLANK : vo.getTelephone());
                    if ( null!=callTaskDTO.getRobotContent() && callTaskDTO.getRobotContent().contains("#factoryName#") ){
                        if (!callTaskDTO.getCallColumn().contains("厂家名称")) {
                            callTaskDTO.getCallColumn().add("厂家名称");
                        }
                        array.add(6, StringUtils.isEmpty(dto.getFactoryName())?"":dto.getFactoryName());
                    }
                    break;
                case WarnStrategyConst.WARN_STRATEGY_AGAIN_JOB:
                    array.add(0, vo.getTelephone() == null ? Constants.BLANK : vo.getTelephone());
                    array.add(1, dto.getPosition() == null ? Constants.BLANK : dto.getPosition());
                    array.add(2, dto.getOrgName() == null ? Constants.BLANK : dto.getOrgName());
                    array.add(3, dto.getOrgPhone()== null ? Constants.BLANK : dto.getOrgPhone());
                    if ( null!=callTaskDTO.getRobotContent() && callTaskDTO.getRobotContent().contains("#factoryName#") ){
                        if (!callTaskDTO.getCallColumn().contains("厂家名称")) {
                            callTaskDTO.getCallColumn().add("厂家名称");
                        }
                        array.add(4, StringUtils.isEmpty(dto.getFactoryName())?"":dto.getFactoryName());
                    }
                    break;
                default:
                    break;
            }
            calls.add(array);
        }
        callTaskDTO.setCallList(calls);

        callTaskDTO = xFCallService.addCallExecTimeParam(callTaskDTO,dto.getExt());

        JSONObject jsonObject = null;
        try {
            jsonObject = xFCallService.callPoolCreate(callTaskDTO,dto.getSpId());
        } catch (Exception e) {
            log.error("servicePeriod-xFCallService-callCreate:{}",e);
        }
        JSONArray data =null;
        if (jsonObject != null ) {
            data = jsonObject.getJSONArray("call_ids");
        }
        
        if( !StringUtils.isEmpty(callTaskDTO.getRobotContent()) ){
            dto.setContent(getCallTemplate(dto, callTaskDTO.getRobotContent(), dto.getOrgPhone()));
            log.info("{}-sendCall-话术已自定义，更新话术内容:{}", job, dto.getContent());
        }
        
        log.info("{}-sendCall-发送消息:{}回执消息:{}", job, callTaskDTO, JSONObject.toJSONString(jsonObject));
        // 保存通知记录
        for (int i = 0; i<dto.getPhones().size(); i++) {
            dto.setPhone(dto.getPhones().get(i).getTelephone());
            dto.setLevel(dto.getPhones().get(i).getLevel());
            dto.setNotifyObjType(dto.getPhones().get(i).getNotifyObjType());
            recordService.saveWarningRecord(dto, new Date(), "发送成功", data!=null?data.get(i) + "":"", 2, 0);
        }
    }


    public String getSmsTemplate(SendMessageDTO dto, String phone) {
        return Constants.RUNNING_SMS_SERVICE_PERIOD.replace("#verb#", dto.getVerb())
                .replace("#Time#", dto.getEndDate() == null ? Constants.BLANK : dto.getEndDate())
                .replace("#position#", dto.getPosition() == null ? Constants.BLANK : dto.getPosition())
                .replace("#phone#", phone == null ? Constants.BLANK : phone)
                .replace("#subsName#", dto.getCustName() == null ? Constants.BLANK : dto.getCustName())
                .replace("#address#", dto.getAddress() == null ? Constants.BLANK : dto.getAddress())
                .replace("#IMEI#", dto.getImei() == null ? Constants.BLANK : dto.getImei());

    }

    public String getWxTemplate(SendMessageDTO dto) {
        return Constants.WARNING_WX_SERVICE_PERIOD.replace("#verb#", dto.getVerb())
                .replace("#Time#", dto.getEndDate() == null ? Constants.BLANK : dto.getEndDate())
                .replace("#IMEI#", dto.getImei() == null ? Constants.BLANK : dto.getImei())
                .replace("#subsName#", dto.getCustName() == null ? Constants.BLANK : dto.getCustName())
                .replace("#subsCode#", dto.getSubsCode() == null ? Constants.BLANK : dto.getSubsCode())
                .replace("#address#", dto.getAddress() == null ? Constants.BLANK : dto.getAddress());

    }

    /**
     * 自定义话术格式化
     * @param dto
     * @param robotContent
     * @param phone
     * @return
     */
    public String getCallTemplate(SendMessageDTO dto, String robotContent, String phone) {
        return robotContent.replace("#name#", dto.getOrgName() == null ? Constants.BLANK : dto.getOrgName())
                .replace("#address#", dto.getPosition() == null ? Constants.BLANK : dto.getPosition())
                .replace("#verb#", dto.getVerb() == null ? Constants.BLANK : dto.getVerb())
                .replace("#date#", dto.getEndDate() == null ? Constants.BLANK : dto.getEndDate())
                .replace("#phone#", phone == null ? Constants.BLANK : phone)
                .replace("#factoryName#", dto.getFactoryName() == null ? Constants.BLANK : dto.getFactoryName());
    }

    //告警
    public String getSmsWarningTemplate(Map<String, Object> param, String smsContent) {
        return smsContent.replace("#verb#", param.get("verb") + "")
                .replace("#Time#", param.get("Time") + "")
                .replace("#Date#", param.get("Date") + "")
                .replace("#value#", param.get("value") + "")
                .replace("#position#", param.get("position") + "")
                .replace("#Equipmenttype#", param.get("Equipmenttype") + "")
                .replace("#subsName#", param.get("subsName") + "")
                .replace("#address#", param.get("address") + "")
                .replace("#IMEI#", param.get("IMEI") + "")
                .replace("#phone#", param.get("Name") + "");

    }
}